import { Injectable, Inject } from '@angular/core'
import { HttpInterceptor, HttpRequest, HttpHandler, HttpEvent } from '@angular/common/http'
import { Observable } from 'rxjs'
import { map } from 'rxjs/operators'
import { DA_SERVICE_TOKEN, ITokenService, JWTTokenModel } from '@delon/auth'

@Injectable()
export class AccessTokenInterceptor implements HttpInterceptor {
  constructor(@Inject(DA_SERVICE_TOKEN) private tokenService: ITokenService) {}
  intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<Response>> {
    return next.handle(req).pipe(
      map((res: HttpEvent<Response>) => {
        this.refreshTokenModel(res)
        return res
      }),
    )
  }

  private refreshTokenModel(res): void {
    const headers = res.headers
    if (headers) {
      const token = headers.get('access_token')
      if (!token) {
        return
      }
      const model = new JWTTokenModel()
      model.token = token
      this.tokenService.set(model)
    }
  }
}
